<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2019/3/22
 * Time: 10:50
 */

namespace app\admin\controller;

use \think\Db;
use \think\paginator\driver\Bootstrap;
use \app\admin\model\Resource as ResourceModel;

class Resource extends Main
{

    public $disk_path;//根目录
    public $resourceModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->disk_path = '/files/' . isession('user_id') . '/product/';
        $this->resourceModel = new ResourceModel();
    }

    /**
     * 产品图片资源列表
     * @return mixed
     */
    public function product()
    {
        $files = $this->read_all_dir($this->disk_path);
        $this->page($files, 'page', 20);
        $this->assign('path', $this->disk_path);
        return $this->fetch('product');
    }

    /**
     * @param $data   传入的数组
     * @param string $listRow // 默认为config的参数
     * @param string $page // 在模版分页显示
     * @param string $url
     * @return bool
     */
    public function page($data, $page, $listRow = '', $url = '')
    {
        if (!is_array($data) || empty($data) || empty($page)) {
            return false;
        }
        if (empty($listRow)) {
            $listRow = intval(config('paginate')['list_rows']);  //获取config里面的参数
        }

        $curPage = input('page') ? input('page') : 1;//当前第x页，有效值为：1,2,3,4,5...
        $showData = array_slice($data, ($curPage - 1) * $listRow, $listRow, true);
        $total = count($data);
        $p = Bootstrap::make($showData, $listRow, $curPage, $total, false, [
            'var_page' => 'page',
            'path' => $url,
            'fragment' => '',
        ]);
        $p->appends(get());
        $this->assign('total', $total);
        $this->assign('files', $showData);
        $this->assign($page, $p->render());
    }

    /**
     * 目录下的资源图片
     * @return mixed
     */
    public function productList()
    {
        $name = sget('filename') ? sget('filename') : '';
        $where['user_id'] = isession('user_id');
        $where['path'] = ['like', '%' . $name . '%'];
        $data = $this->resourceModel->getResource($where);
        $list = $data->all();
        if (checkArr($list)) {
            foreach ($list as $key => $value) {
                $list[$key]['size'] = diskTransform($value['size']);
                $list[$key]['postfix'] = strtoupper($value['postfix']);
            }
        }
        $this->assign('data', $data);
        $this->assign('list', $list);
        return $this->fetch('productList');
    }

    /**
     * 删除资源
     */
    public function resourceDel()
    {
        $type = spost('type');
        $path = spost('path');
        $id = ipost('id');
        if ($type == 'file') {
            $res = $this->delFile($path, $id);
        } elseif ($type == 'files') {
            $res = $this->delFiles(post());
        }
        if ($res == true) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 删除文件
     * @param string $path
     * @param string $id
     * @return mixed
     */
    private function delFile($path = '', $id = '')
    {
        $arr['path'] = $path;
        $arr['module'] = 'product';
        $res = $this->resourceModel->delOneResource($arr, $id);
        if ($res == true) {
            unlink(server('DOCUMENT_ROOT') . iconv("utf-8", "gb2312", $path));
        }
        return $res;
    }

    /**
     * 删除文件夹
     * @param string $data
     * @return bool
     */
    private function delFiles($data = '')
    {
        $where['user_id'] = isession('user_id');
        $where['module'] = 'product';
        $where['path'] = ['like', '%' . $data['name'] . '%'];
        $this->resourceModel->delResource($where);
        $path = server('DOCUMENT_ROOT') . $data['path'] . $data['name'];
        $opath = iconv('utf-8', 'gb2312', $path);//旧文件名
        $npath = iconv('utf-8', 'gb2312', $path . 'del');//新文件名
        if (is_dir($opath)) {//判断有没有旧的目录
            if (rename($opath, $npath)) {//修改目录
                $this->insertFileDel($npath);
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 删除文件夹路径存入删除库
     * @param string $path
     * @return int|string
     */
    private function insertFileDel($path = '')
    {
        $insert = [
            'path' => $path,
            'user_id' => isession('user_id')
        ];
        return DB::name('del_file')->insert($insert);
    }

    /**
     * 遍历文件夹
     * @param $dir
     * @param string $size
     * @return array
     */
    private function read_all_dir($dir, $size = '')
    {
        $dir = server('DOCUMENT_ROOT') . iconv("utf-8", "gb2312", $dir);
        $result = [];
        if (is_dir($dir) && $handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                $arr = [];
                if ($file != '.' && $file != '..') {
                    if (is_dir($dir . '/' . $file) && (strpos($file, 'del') == false) && ($file != 'temfile')) {
                        $arr['time'] = date("Y-m-d H:i:s", filemtime($dir . $file)); //最近修改时间
                        $arr['size'] = $size ? filesize($dir . $file) : $this->getRealSize(filesize($dir . $file)); //文件大小
                        $arr['name'] = $name = iconv("gb2312", "utf-8", $file); //文件名;
                        clearstatcache();
                        $arr['type'] = '文件夹'; //文件类型
                        $result[] = $arr;
                    }
                }
            }
            closedir($handle);
        }
        return $result;
    }

    /**
     * 转换文件大小的单位
     * @param $size
     * @return string
     */
    private function getRealSize($size)
    {
        $kb = 1024;   // Kilobyte
        $mb = 1024 * $kb; // Megabyte
        $gb = 1024 * $mb; // Gigabyte
        $tb = 1024 * $gb; // Terabyte
        if ($size < $kb) {
            return $size . " B";
        } else if ($size < $mb) {
            return round($size / $kb, 2) . " KB";
        } else if ($size < $gb) {
            return round($size / $mb, 2) . " MB";
        } else if ($size < $tb) {
            return round($size / $gb, 2) . " GB";
        } else {
            return round($size / $tb, 2) . " TB";
        }
    }
}